package com.lv.suyiyong.hfr.ui

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.lv.common.base.BaseActivity
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.service.bean.FindProsBean
import com.lv.service.bean.GoodsBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.CouponSearch
import com.lv.service.repo.CouponSearchDbHelper
import com.lv.service.repo.HomeSearch
import com.lv.service.repo.WholeSalerSearch
import com.lv.service.repo.WholeSalerSearchDbHelper
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityCommonSearchBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：公共搜索
 */
@Route(path = ARoutUtils.CommonSearchActivity)
class CommonSearchActivity : BaseActivity<ActivityCommonSearchBinding>(), View.OnClickListener {
    @Autowired(name = "search")
    @JvmField
    var search: String = ""

    @Autowired(name = "searchCode")
    @JvmField
    var mSearchCode: String = "0"//0 wholesaler 1 coupon

    private val mParmasMap = mutableMapOf<String, String>()

    private var mSearch = mutableListOf<String>()
    private var mHotSearch = mutableListOf<String>()
    private val mViewList = mutableListOf<View>()
    private val mHotViewList = mutableListOf<View>()
    private var mExpend: Boolean = false //是否展开
    private var mHotExpent: Boolean = false //是否展开
    private var mLoading: Boolean = true //是否有
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val serviceViewModel: ServiceViewModel by viewModel()
    override fun getLayoutRes() = R.layout.activity_common_search
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@CommonSearchActivity, viewTop)
            initSingleClickListener(ivBackTop, vSearch, ivClear)
        }
    }


    override fun initConfig() {
        super.initConfig()

        if (search.isNotEmpty()) {
            mBinding.searchVM = search
        }
        mBinding.etSearch.paint.isFakeBoldText = !TextUtils.isEmpty(search)
        findPros()
    }


    override fun initData() {
        super.initData()
        addFlowView()
    }


    private fun findPros() {
        mParmasMap["hotSearch"] = "1"
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    serviceViewModel.findPros(mParmasMap)
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<FindProsBean> { code, data, message, result ->
                val hotSearch = data?.hotSearch
                mHotSearch.clear()
                hotSearch?.let {
                    mHotSearch.addAll(hotSearch)
                }
                setHotFlowData()
            }
            onBizError<GoodsBean> { code, message, data ->

            }
        }
        data.onFailure {

        }
    }

    override fun initEvents() {
        super.initEvents()

        mBinding.etSearch.setOnEditorActionListener { v, actionId, event ->
            KeyboardUtils.hideSoftInput(mBinding.etSearch)
            search = mBinding.etSearch.text.toString().trim()
            if (TextUtils.isEmpty(search)) {
                showToast("请输入要搜索的关键字")
                false
            } else {
                saveSearchWord(search)
                true
            }
        }

        mBinding.etSearch.addTextChangedListener { text ->
            if (TextUtils.isEmpty(text)) {
                search = ""
                mBinding.etSearch.paint.isFakeBoldText = false
            } else {
                search = text.toString()
                mBinding.etSearch.paint.isFakeBoldText = true
            }
        }

    }

    private fun saveSearchWord(searchWord: String) {

        for (i in 0 until mSearch.size) {
            if (mSearch[i] == searchWord) {
                mSearch.removeAt(i)
                break
            }
        }
        mSearch.add(0, searchWord)
        mBinding.llHistory.visibility = View.VISIBLE
        mBinding.flowViewZ.visibility = View.VISIBLE
        setFlowData()
        mBinding.searchVM = searchWord
//        viewModel.liveSearchData.value = searchWord
        search = searchWord

        when (mSearchCode) {
            "0" -> {
                val homeSearch = WholeSalerSearch(searchWord, searchWord, false)
                WholeSalerSearchDbHelper.insertWholeSalerSearch(
                    this@CommonSearchActivity, homeSearch
                )
                ARouter.getInstance().build(ARoutUtils.WholeSalerSearchResultActivity)
                    .withString("search", search).navigation()
            }

            "1" -> {
                val homeSearch = CouponSearch(searchWord, searchWord, false)
                CouponSearchDbHelper.insertCouponSearch(
                    this@CommonSearchActivity, homeSearch
                )
                ARouter.getInstance().build(ARoutUtils.CouponSearchResultActivity)
                    .withString("search", search).navigation()
            }

        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back_top -> finish()
            R.id.iv_clear -> {
                when (mSearchCode) {
                    "0" -> {
                        WholeSalerSearchDbHelper.deleteAllWholeSalerSearch(this@CommonSearchActivity)
                    }

                    "1" -> {
                        CouponSearchDbHelper.deleteAllCouponSearch(this@CommonSearchActivity)
                    }

                }
                mBinding.flowViewZ.removeAllViews()
                mBinding.llHistory.visibility = View.GONE
                mBinding.flowViewZ.visibility = View.GONE
                mBinding.etSearch.setText("")
                search = ""
                mSearch.clear()
            }

            R.id.v_search -> {
                KeyboardUtils.hideSoftInput(mBinding.etSearch)
                search = mBinding.etSearch.text.toString().trim()
                if (TextUtils.isEmpty(search)) {
                    showToast("请输入要搜索的关键字")
                    false
                } else {
                    saveSearchWord(search)
                    true
                }
            }
        }
    }

    private fun addFlowView() {

        lifecycleScope.launch {
            val homeSearch = mutableListOf<HomeSearch>()

            when (mSearchCode) {
                "0" -> {
                    val list = WholeSalerSearchDbHelper.getAllWholeSalerSearch(
                        this@CommonSearchActivity
                    )
                    list.forEach { homeSearch.add(HomeSearch(it._id, it.name, it.search)) }
                }

                "1" -> {
                    val list = CouponSearchDbHelper.getAllCouponSearch(
                        this@CommonSearchActivity
                    )
                    list.forEach { homeSearch.add(HomeSearch(it._id, it.name, it.search)) }
                }

            }

            val reversed = homeSearch.reversed()
            reversed.let {
                mSearch.clear()
                reversed.forEach { item ->
                    mSearch.add(item.name ?: "")
                }
            }


            if (mSearch.isEmpty()) {
                mBinding.llHistory.visibility = View.GONE
                mBinding.flowViewZ.visibility = View.GONE
            } else {
                mBinding.llHistory.visibility = View.VISIBLE
                mBinding.flowViewZ.visibility = View.VISIBLE
            }

            setFlowData()

            mBinding.flowViewZ.setOnTagClickListener { view, position ->
                val key = mSearch[position]
                saveSearchWord(key)

            }


        }
    }

    private fun setFlowData() {
        mViewList.clear();
        for (i in 0 until mSearch.size) {
            val textChild = LayoutInflater.from(this@CommonSearchActivity)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout,
                    mBinding.flowViewZ, false
                ) as TextView
            textChild.text = mSearch[i]
            mViewList.add(textChild)
        }

        mBinding.flowViewZ.setChildren(mViewList)
        mBinding.flowViewZ.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mBinding.flowViewZ.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val lineCount = mBinding.flowViewZ.lineCount //行数
                val twoLineViewCount = mBinding.flowViewZ.twoLineViewCount   //前两行里面view的个数
                val expandLineViewCount = mBinding.flowViewZ.expandLineViewCount  ///展开时显示view的个数
                if (lineCount > 2 && !mExpend) {  //默认展示2行，其余折叠收起，最多展示5行
                    initIvClose(twoLineViewCount, expandLineViewCount);
                } else {
                    initIvOpen(twoLineViewCount, expandLineViewCount)
                }

            }
        })
    }

    /**
     * 热门搜索
     */
    private fun setHotFlowData() {
        mHotViewList.clear()
        for (element in mHotSearch) {
            val textChild = LayoutInflater.from(this@CommonSearchActivity)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout, mBinding.flowViewHot, false
                ) as TextView
            textChild.text = element
            mHotViewList.add(textChild)
        }
        mBinding.flowViewHot.setChildren(mHotViewList)
        mBinding.flowViewHot.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mBinding.flowViewHot.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val lineCount = mBinding.flowViewHot.lineCount  //行数
                val twoLineViewCount = mBinding.flowViewHot.twoLineViewCount  //前两行里面view的个数
                val expandLineViewCount = mBinding.flowViewHot.expandLineViewCount ///展开时显示view的个数
                if (lineCount > 2 && !mHotExpent) {  //默认展示2行，其余折叠收起，最多展示5行
                    initIvHotClose(twoLineViewCount, expandLineViewCount);
                } else {
                    initIvHotOpen(twoLineViewCount, expandLineViewCount)
                }

            }
        })
        mBinding.flowViewHot.setOnTagClickListener { view, position ->
            val key = mHotSearch[position]
            saveSearchWord(key)

        }

    }


    private fun initIvClose(twoLineViewCount: Int, expandLineViewCount: Int) {
        mExpend = false
        mViewList.clear()
        for (i in 0 until twoLineViewCount) {
            val textView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout,
                    mBinding.flowViewZ,
                    false
                ) as TextView
            textView.text = mSearch[i]
            mViewList.add(textView)
        }

        if (expandLineViewCount > twoLineViewCount) {
            //展开按钮
            val imageView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.img_record_search_tag,
                    mBinding.flowViewZ,
                    false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_down)
            imageView.setOnClickListener { v: View? ->
                initIvOpen(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mViewList.add(imageView)
        }
        mBinding.flowViewZ.setChildren(mViewList)
        mBinding.flowViewZ.viewTreeObserver?.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mBinding.flowViewZ.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val lineCount: Int = mBinding.flowViewZ.lineCount
                val twoLineViewCount: Int = mBinding.flowViewZ.twoLineViewCount
                if (lineCount > 2) {
                    initIvClose(
                        twoLineViewCount - 1,
                        mBinding.flowViewZ.expandLineViewCount
                    )
                }
            }
        })
    }

    private fun initIvOpen(twoLineViewCount: Int, expandLineViewCount: Int) {
        mExpend = true
        mViewList.clear()
        for (i in 0 until expandLineViewCount) {
            val textView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout,
                    mBinding.flowViewZ,
                    false
                ) as TextView
            textView.text = mSearch[i]
            mViewList.add(textView)
        }
        if (expandLineViewCount > twoLineViewCount) {
            //收起按钮
            val imageView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.img_record_search_tag,
                    mBinding.flowViewZ,
                    false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_up)
            imageView.setOnClickListener { v: View? ->
                initIvClose(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mViewList.add(imageView) //不需要的话可以不添加
        }
        mBinding.flowViewZ.setChildren(mViewList)
    }

    private fun initIvHotClose(twoLineViewCount: Int, expandLineViewCount: Int) {
        mHotExpent = false
        mHotViewList.clear()
        for (i in 0 until twoLineViewCount) {
            val textView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout, mBinding.flowViewHot, false
                ) as TextView
            textView.text = mHotSearch[i]
            mHotViewList.add(textView)
        }

        if (expandLineViewCount > twoLineViewCount) {
            //展开按钮
            val imageView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.img_record_search_tag, mBinding.flowViewHot, false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_down)
            imageView.setOnClickListener { v: View? ->
                initIvHotOpen(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mHotViewList.add(imageView)
        }
        mBinding.flowViewHot.setChildren(mHotViewList)
        mBinding.flowViewHot.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mBinding.flowViewHot.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val lineCount: Int = mBinding.flowViewHot.lineCount
                val twoLineViewCount: Int = mBinding.flowViewHot.twoLineViewCount
                if (lineCount > 2) {
                    initIvHotClose(
                        twoLineViewCount - 1,
                        mBinding.flowViewHot.expandLineViewCount
                    )
                }
            }
        })
    }

    private fun initIvHotOpen(twoLineViewCount: Int, expandLineViewCount: Int) {
        mHotExpent = true
        mHotViewList.clear()
        for (i in 0 until expandLineViewCount) {
            val textView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.text_tag_search_layout, mBinding.flowViewHot, false
                ) as TextView
            textView.text = mHotSearch[i]
            mHotViewList.add(textView)
        }
        if (expandLineViewCount > twoLineViewCount) {
            //收起按钮
            val imageView = LayoutInflater.from(this)
                .inflate(
                    com.lv.common.R.layout.img_record_search_tag,
                    mBinding.flowViewHot, false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_up)
            imageView.setOnClickListener { v: View? ->
                initIvHotClose(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mHotViewList.add(imageView) //不需要的话可以不添加
        }
        mBinding.flowViewHot.setChildren(mHotViewList)
    }

}